//
//  HEGoodsCommentsCell.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/4.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEGoodsCommentsCell.h"
#import "HDRatingStarView.h"
#import "KNPhotoBrowser.h"


@interface HEGoodsCommentsCell ()

@property (strong, nonatomic) UIImageView *userHeadImg;
@property (strong, nonatomic) UILabel *nameLb;
@property (strong, nonatomic) UILabel *timeLb;

@property (nonatomic, strong) HDRatingStarView *startView;
@property (nonatomic, strong) UILabel *cotentLb;
@property (nonatomic, strong) ImagesView *images;

@end

@implementation HEGoodsCommentsCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        // Fix the bug in iOS7 - initial constraints warning
        self.contentView.bounds = [UIScreen mainScreen].bounds;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.backgroundColor = KWhiteColor;
        self.qmui_borderPosition = QMUIViewBorderPositionBottom;
        self.qmui_borderColor = KHexColor(@"F5F5F5");
        
        [self initUI];
        [self setpData];
    }
    return self;
}

- (void)initUI {
    
    _userHeadImg = [[UIImageView alloc] init];
    _userHeadImg.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:_userHeadImg];
    
    _nameLb = [[UILabel alloc] init];
    _nameLb.font = DYFont(16);
    [self.contentView addSubview:_nameLb];
    
    _timeLb = [[UILabel alloc] init];
    _timeLb.font = DYFont(14);
    _timeLb.textColor = KHexColor(@"757575");
    [self.contentView addSubview:_timeLb];
    
    [_userHeadImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).mas_offset(15);
        make.width.height.mas_equalTo(50);
        make.left.equalTo(self.contentView).mas_offset(15);
    }];
    
    [_timeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userHeadImg);
        make.right.equalTo(self.contentView.mas_right).mas_offset(-15);
    }];
    [_timeLb setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    
    [_nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userHeadImg);
        make.left.equalTo(_userHeadImg.mas_right).mas_offset(5);
        make.right.equalTo(_timeLb.mas_left).mas_offset(-5);
        make.height.mas_offset(15);
     }];
    [_timeLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [_nameLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
}

- (void)setpData {
     
    _userHeadImg.layer.masksToBounds = YES;
    _userHeadImg.layer.cornerRadius = 25;

    // 星星评分
    _startView = [[HDRatingStarView alloc] init];
    _startView.renderColor = KHexColor(@"F67605");
    _startView.defaultColor = KHexColor(@"CDCDCD");
    _startView.allowTouchToSelectScore = NO;
    _startView.score = 0;
    _startView.starWidth = 15;
    _startView.starImage = IMAGE_NAMED(@"rating_sel");
    [self.contentView addSubview:_startView];
   
    // 评论
    _cotentLb = [UILabel new];
    _cotentLb.font = DYFont(15);
    _cotentLb.numberOfLines = 0;
    [self.contentView addSubview:_cotentLb];
    
    // 可去掉
    _cotentLb.preferredMaxLayoutWidth = KScreenWidth - 20 - 50;
    [_cotentLb setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    
    [_startView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.top.equalTo(_nameLb.mas_bottom).mas_offset(5);
      make.left.equalTo(_nameLb.mas_left);
      make.right.equalTo(self.contentView.mas_right).mas_offset(-10);
      make.height.mas_greaterThanOrEqualTo(15);
    }];

    [_cotentLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_startView.mas_bottom).mas_offset(10);
        make.left.equalTo(_nameLb.mas_left);
        make.right.equalTo(self.contentView.mas_right).mas_offset(-10);
        make.height.mas_equalTo(0).priorityLow();
    }];
 
    ImagesView *images = [[ImagesView alloc] init];
//    images.backgroundColor = UIColor.orangeColor;
    [self.contentView addSubview:images];
    [images mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_cotentLb.mas_bottom).mas_offset(10);
        make.left.equalTo(_nameLb.mas_left);
        make.right.equalTo(self.contentView.mas_right).mas_offset(-10);
        make.height.mas_equalTo(0).priorityLow();
        make.bottom.mas_equalTo(self.contentView).offset(-10).priorityLow();
    }];
    
    _images = images;
}

- (void)setModel:(HEGoodsCommentModel *)model {
    
    _model = model;
    [_userHeadImg sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:IMAGE_NAMED(@"noImage")];
    
    _startView.score = model.stars;
    _nameLb.text = model.memberName;
    _cotentLb.text = model.consultContent;
    _timeLb.text = model.kconsultAddtime;
    
    if (model.kemail.count == 0) {
        [self.images mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0).priorityMedium();
            make.bottom.mas_equalTo(self.contentView).priorityMedium();
        }];
    }else {
    }
    _images.imagesArray = model.kemail.mutableCopy;
}

@end

 



@interface ImagesView ()<KNPhotoBrowserDelegate>

@property (nonatomic, strong) NSMutableArray *ButtonArray;
@property (nonatomic, strong) NSMutableArray *itemsArr;
@property (nonatomic, strong) KNPhotoBrowser *photoBrowser;

@end

static CGFloat margin = 10.f;
#define ButtonW (KScreenWidth - 80 - margin * 2) / 3.0

@implementation ImagesView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI];
    }
    return self;
}

-(void)setUpUI {
   
//    NSInteger line = self.imagesArray.count%3;
    for (int i = 0; i < 9; i++) {
        
        NSInteger row1 = i/3;
        NSInteger colum = i%3;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView setUserInteractionEnabled:YES];
        [imageView setBackgroundColor:[UIColor grayColor]];
        [imageView setContentMode:UIViewContentModeTop | UIViewContentModeLeft | UIViewContentModeRight];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        imageView.frame = CGRectMake((margin + ButtonW)*colum, (margin + ButtonW)*row1, ButtonW, ButtonW);
        imageView.hidden = YES;
        imageView.tag = i;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [self.ButtonArray addObject:imageView];
        [self addSubview:imageView];
    }
}

-(void)setImagesArray:(NSMutableArray *)imagesArray {
    _imagesArray = imagesArray;
     NSInteger count = (imagesArray.count - 1)/3  +1;
        
    [self.itemsArr removeAllObjects];
    [self.ButtonArray enumerateObjectsUsingBlock:^(UIButton *  _Nonnull button, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (idx<self.imagesArray.count) {
            
            button.hidden = NO;
            UIImageView *imageView = self.ButtonArray[idx];
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.imagesArray[idx]] placeholderImage:[UIImage imageNamed:@"noImage"] ];
 
            KNPhotoItems *items = [[KNPhotoItems alloc] init];
            items.url = imagesArray[idx] ;
            items.sourceView = imageView;
            [self.itemsArr addObject:items];
            
            UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bigImage:)];
            imageView.userInteractionEnabled=YES;
            [imageView addGestureRecognizer:tapGes];
            
        }else{
            button.hidden = YES;
        }
    }];
    
    if (imagesArray.count == 0) {
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0).priorityMedium();
        }];
    }else{
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((margin + ButtonW)*count).priorityMedium();
        }];
    }
}


#pragma mark - Getter

- (NSMutableArray *)ButtonArray {
    if(!_ButtonArray){
        _ButtonArray = [[NSMutableArray alloc] init];
    }
    return _ButtonArray;
}

#pragma mark -
- (NSMutableArray *)itemsArr {
    if (!_itemsArr) {
        _itemsArr = [NSMutableArray array];
    }
    return _itemsArr;
}

- (void)bigImage:(UITapGestureRecognizer *)tap {
 
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    photoBrowser.itemsArr = [self.itemsArr copy];
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedRightTopBtn = true;
    photoBrowser.isNeedPictureLongPress = true;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;
    photoBrowser.currentIndex = tap.view.tag;
    photoBrowser.delegate = self;
    [photoBrowser present];
    
    _photoBrowser = photoBrowser;
}

/* photoBrowser 右上角按钮的点击 */
- (void)photoBrowserRightOperationAction{
    
    __weak typeof(self) weakself = self;
    KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"保存"].mutableCopy destructiveArray:@[@"0"].mutableCopy actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
 
            [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
        }
    }];
    
    [actionSheet show];
}

/// long press
/// @param photoBrowser pb
/// @param longPress press
- (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [photoBrowser setImmediatelyPlayerRate:2];
    }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
        [photoBrowser setImmediatelyPlayerRate:1];
    }
}


- (void)toSaveImage:(NSURL *)url {
 
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    if ([manager cacheKeyForURL:url]) {
       [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
           // 保存图片到相册中
           UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }];
        return;
    }
    else {
        //从网络下载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];
        // 保存图片到相册中
        UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }
}
//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    if (error != NULL) {
        [Dialog toast:@"图片保存失败" delay:2.0];
    }
    else  // No errors
    {
        [Dialog toast:@"图片保存成功" delay:2.0];
    }
}



@end
